package com.example.testproj.ipc;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class IpcTestService extends Service {
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("qin","收到消息"+msg.getData().getString("word"));
           Messenger messenger= msg.replyTo;
           Message message=new Message();
            Bundle bundle=new Bundle();
            bundle.putString("word","哈哈哈哈，我是通过bundle通讯");
            message.setData(bundle);
          // message.obj="啊哈哈,我收到了,可惜你不能跨进程";
            try {
                messenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    private final Messenger messenger;

    public IpcTestService() {
        messenger = new Messenger(handler);
        ExecutorService executorService= Executors.newSingleThreadExecutor();
        for (int i=0;i<20;i++){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                  //  Log.d("qin","我是线程产生的消息");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return messenger.getBinder();
    }


}
